﻿using Hidistro.Core;
using Juse.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using wnxd.Web;

namespace Hidistro.UI.Web
{
    class InitPage : Enter, IHttpHandler
    {
        public InitPage()
        {
            this.HttpHandlerPath = "InitPageAjax.aspx";
        }
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            string url = Server.UrlDecode(this.Request["Url"]);
            string action = Server.UrlDecode(this.Request["action"]);
            if (action != "beat" && this.Request.Cookies["URL"] == null && url.IndexOf("ResourceNotFound") < 0 && url.IndexOf("ErrorInfo") < 0)
            {
                HttpCookie cookie = new HttpCookie("URL", url);
                this.Response.Cookies.Add(cookie);
                Globals.SyncCookie(cookie);
            }
            if (!string.IsNullOrEmpty(action) && action == "beat")
            {
                UserBehavior pb = new UserBehavior();
                Dictionary<string, DateTime> list = pb.GetBeatDic();
                if (list == null)
                {
                    list = new Dictionary<string, DateTime>();
                }
                string guid = "";
                if (context.Request.Cookies.Get("beat") == null)
                {
                    guid = Guid.NewGuid().ToString();
                    HttpCookie cookie = new HttpCookie("beat", guid);
                    this.Response.Cookies.Add(cookie);
                    Globals.SyncCookie(cookie);
                    list.Add(guid, DateTime.Now);
                }
                else
                {
                    guid = context.Request.Cookies.Get("beat").Value;
                    if (list.Count == 0 || !list.Keys.Contains(guid))
                    {
                        list.Add(guid, DateTime.Now);
                    }
                    else
                    {
                        list[guid] = DateTime.Now;
                    }
                }
                List<string> keys = new List<string>();
                foreach (var item in list)
                {
                    TimeSpan ts = DateTime.Now - item.Value;
                    if (ts.TotalSeconds >= 5)
                    {
                        keys.Add(item.Key);
                    }
                }
                foreach (var item in keys)
                {
                    list.Remove(item);
                }
                pb.SetBeatDic(list);
            }
        }
    }
}
